package com.example.skytakeoutserver.util

import com.example.serverbase.ext.Log
import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import org.springframework.stereotype.Component
import java.nio.charset.StandardCharsets

@Component
class JwtUtil {
    /**
     * 从配置文件获取密钥
     */
    fun generateToken(secretKey: String?, username: String?): String {
        return Jwts.builder()
            .setSubject(username)
            .signWith(
                SignatureAlgorithm.HS512,
                secretKey?.toByteArray(StandardCharsets.UTF_8)
            )
            .compact()
    }


    fun parseJWT(secretKey: String?, token: String?): Claims? {
        try {
            val claims = Jwts.parser()
                .setSigningKey(
                    secretKey!!.toByteArray(
                        StandardCharsets.UTF_8
                    )
                )
                .parseClaimsJws(token).body
            return claims
        } catch (ex: Exception) {
            Log.error(ex.message, ex)
            return null
        }
    }


    fun validateToken(secretKey: String?, token: String?): Boolean {
        try {
            val claims = Jwts.parser()
                .setSigningKey(secretKey?.toByteArray(StandardCharsets.UTF_8))
                .parseClaimsJws(token).body
            return null != claims.get("userId", Long::class.java)!!
        } catch (ex: Exception) {
            Log.error(ex.message, ex)
            return false
        }
    }

}